import { Component, OnInit }           from '@angular/core';
import { ActivatedRoute }              from "@angular/router";
import { HttpClient }                  from "@angular/common/http";
import { zip }                         from "rxjs";
import { Title }                       from "@angular/platform-browser";
import { Result }                      from "../shared/model/result";
import { DialogService, ToastService } from "ngx-weui";

@Component({
    selector   : 'app-payment',
    templateUrl: './payment.component.html',
    styleUrls  : [ './payment.component.less' ]
})
export class PaymentComponent implements OnInit
{
    price: number;
    private isWx = true;
    private code: string;
    private deviceId;
    
    constructor( private route: ActivatedRoute,
                 private http: HttpClient,
                 private titleService: Title,
                 public toastService: ToastService,
                 private dialog: DialogService )
    {
        titleService.setTitle("支付")
    }
    
    
    ngOnInit()
    {
        if ( /MicroMessenger/.test(navigator.userAgent) )
        {
            this.checkwx();
        }
        else
        {
            this.isWx = false;
            this.deviceId = this.route.snapshot.queryParams["deviceId"];
            this.loadPrice(this.deviceId)
        }
    }
    
    loadPrice( deviceId: string | (string | null)[] )
    {
        this.http.get<number>(`api/payment/price?deviceId=` + deviceId).subscribe((value:any) =>
        {
            this.price = value.data
        }, error => alert(error.message))
    }
    
    onPay()
    {
        if ( this.isWx )
        {
            let openId = sessionStorage.getItem('openId');
            console.log(openId);
            if ( openId )
                this.http.get(`api/payment/${ this.deviceId }?openId=${ openId }`)
                    .subscribe(( res: Result<any> ) =>
                    {
                        if ( res.success )
                        {
                            const data = res.data;
                            WeixinJSBridge.invoke(
                                'getBrandWCPayRequest', {
                                    'appId'    : data.appId,     //公众号名称，由商户传入
                                    'timeStamp': `${ data.timeStamp }`,         //时间戳，自1970年以来的秒数
                                    'nonceStr' : data.nonceStr, //随机串
                                    'package'  : data.package,
                                    'signType' : data.signType,         //微信签名方式：
                                    'paySign'  : data.sign
                                },
                                function ( cb: any )
                                {
                                    if ( cb.err_msg == 'get_brand_wcpay_request:ok' )
                                    {
                                        WeixinJSBridge.invoke('closeWindow', {}, function ( res )
                                        {
                                        });
                                    }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                                }
                            );
                        }
                        else
                        {
                            this.dialog.show({
                                title  : '错误',
                                content: res.msg,
                                skin   : 'android',
                            }).subscribe(value => this.close())
                        }
                        
                    }, error =>
                    {
                        this.dialog.show({
                            title  : '错误',
                            content: "支付失败，稍后重试",
                            skin   : 'android',
                        }).subscribe(value => this.close())
                    })
        }
        else
        {
            //支付宝支付
            this.http.get(`api/payment/${ this.deviceId }?openId=alipay`).subscribe(( res: any ) =>
            {
                if (res.success ){
                    const newWindow = window.open('about:blank', '_blank');
                    newWindow!.document.write(res.data);//后台返回的html字符串
                    newWindow!.document.title = '支付';
                    newWindow!.document.close();
                }else {
                    this.dialog.show({
                        title  : '错误',
                        skin   : 'android',
                        content: res.msg,
                    }).subscribe(() => this.close())
                }
               
            }, error =>
            {
                alert("暂时无法支付，请稍后再试..")
            })
        }
    }
    
    close()
    {
        WeixinJSBridge.invoke('closeWindow', {}, function ( res )
        {
        });
    }
    
    private checkwx()
    {
        let openId = sessionStorage.getItem("openId");
        console.log(openId);
        if ( !openId )
        {
            this.code = this.route.snapshot.queryParams["code"];
            this.deviceId = this.route.snapshot.queryParams["deviceId"];
            if ( this.code )
            {
                this.toastService.show("加载中", 0, null, "loading");
                zip(
                    this.http.get<any>(`api/wx/openid?code=${ this.code }`),
                    this.http.get<Result<number>>(`api/payment/price?deviceId=` + this.deviceId)
                ).subscribe(( [ { token }, price ] ) =>
                {
                    this.toastService.destroyAll();
                    console.log(token);
                    if ( token )
                    {
                        sessionStorage.setItem('openId', token.openId);
                    }
                    
                    if ( price && price.success )
                        this.price = price.data;
                    else
                    {
                        this.dialog.show({
                            title  : '错误',
                            skin   : 'android',
                            content: price.msg,
                        }).subscribe(() => this.close())
                    }
                    
                }, error =>
                {
                    this.toastService.destroyAll();
                    this.dialog.show({
                        title  : '错误',
                        skin   : 'android',
                        content: "支付失败，稍后重试",
                    }).subscribe(value => this.close())
                })
                // this.getOpenId(this.code);
            }
            else
            {
                this.getCode();
            }
        }
        else
        {
            this.deviceId = this.route.snapshot.queryParams["deviceId"];
            this.http.get<Result<number>>(`api/payment/price?deviceId=` + this.deviceId).subscribe(value =>
            {
                if ( value.success )
                {
                    this.price = value.data
                }
                else
                {
                    this.dialog.show({
                        title  : '错误',
                        skin   : 'android',
                        content: value.msg,
                    }).subscribe(() => this.close())
                }
            })
        }
    }
    
    private getCode()
    {
        let currentUrl = encodeURIComponent(window.location.href);
        console.log(currentUrl);
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8967c70393c474ea&redirect_uri=${ currentUrl }&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
    }
}
